<template>
  <div>
    <Row class="y_query_right">
      <Button type="primary" icon="md-arrow-forward" class="y_condition" :disabled="noSelectedRows" @click="importManyToFormalLib()">导入正式库</Button>
      <Divider></Divider>
<!--      <Select v-model="searchParam.state" class="y_condition" style="text-align: left;" clearable placeholder="状态">-->
<!--        <Option v-for="(item, index) in dict.productStates" :key="index" :value="item.value">{{item.label}}</Option>-->
<!--      </Select>-->
      <Cascader v-model="searchParam.categories" :data="categoryTreeData" change-on-select placeholder="采集分类" class="y_condition" style="text-align: left;"></Cascader>

      <Input type="text" v-model.trim="searchParam.pCode" placeholder="货源编号" clearable class="y_condition"></Input>
      <Input type="text" v-model.trim="searchParam.shopId" placeholder="供货商编号" clearable class="y_condition"></Input>
      <Input v-model.trim="searchParam.tag" class="y_condition" placeholder="标签"></Input>
      <Select v-model="searchParam.importState" placeholder="导入状态" clearable class="y_condition" style="text-align: left;">
        <Option v-for="(item, index) in dict.importStates" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Select v-model="searchParam.from" class="y_condition" style="text-align: left;" clearable placeholder="平台">
        <Option v-for="(item, index) in dict.productSources" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Select v-model="searchParam.stationBanned" class="y_condition" style="text-align: left;" clearable placeholder="屏蔽状态">
        <Option :value="0">未屏蔽</Option>
        <Option :value="1">已屏蔽</Option>
      </Select>
      <Select v-model="searchParam.siteCode" class="y_condition" style="text-align: left;" placeholder="站点">
        <Option v-for="(item, index) in dict.siteCodes" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Input type="text" v-model.trim="searchParam.author" placeholder="采集人" clearable class="y_condition"></Input>
      <Checkbox v-model="searchParam.isAuditable">属于本站</Checkbox>
      <DatePicker type="daterange" :options="datePickerOptions" placement="bottom-end" :editable="false" placeholder="审核时间"
                  @on-change="changeTimeParam" class="y_condition" style="max-width: 200px; width: 200px; text-align: left;"></DatePicker>
      <Button type="primary" icon="md-search" class="y_condition" @click="search()">查询</Button>
    </Row>

<!--    <Table :columns="tableColumns" :data="productList" @on-selection-change="changeSelectedRows" border style="margin-top: 20px;"></Table>-->
    <div v-if="productList.length > 0" style="text-align: left; margin: 1rem 0 0 25px;">
      <Checkbox v-model="allCheck.isChecked" :indeterminate="allCheck.indeterminate" @on-change="toggleAllCheck" style="vertical-align: middle;">全选</Checkbox>
    </div>
    <List class="data-list" border>
      <div v-if="productList.length > 0">
        <CheckboxGroup v-model="selectedIds">
          <ListItem v-for="(item, index) in productList" :key="item.id" class="list-item">
            <Row style="width: 100%;">
              <Col :span="3" :xxl="3" :xl="4" :lg="5" :md="6" :sm="9" :xs="12" style="text-align: left; line-height: 100%;">
                <div class="item-checkbox">
                  <Checkbox :label="item.id" :disabled="hasBanned(item)"><span></span></Checkbox>
                </div>
                <div class="item-img" @click="showBigImage(getProductOriginalImg(item))">
                  <img :src="getProductImg(item)" style="max-width: 100%;"/>
                </div>
              </Col>
              <Col :span="21" :xxl="21" :xl="20" :lg="19" :md="18" :sm="15" :xs="12" style="padding-left: 0.5rem">
                <div class="item-top">
                  <p style="font-weight: bold; text-align: left;">
                    {{item.title}}
                  </p>
                  <Tag color="gray" v-if="hasBanned(item)">已屏蔽</Tag>
                </div>

                <div class="item-content">
                  <div>
                    <KeyValueView title="英文名称" :value="item.titleEn"></KeyValueView><br/>
                    <KeyValueView title="货源编号">
                      {{item.pCode}}
                    </KeyValueView>

                    <KeyValueView title="标签">
                      <span v-if="item.tags!=null && item.tags.length>0">{{item.tags.join("，")}}</span>
                      <span v-else>无</span>
                    </KeyValueView>
                    <br/>
                  </div>
                  <div>
                    <KeyValueView title="采集分类" v-if="item.categoryNames!=null && item.categoryNames.length > 0">{{item.categoryNames.join(" / ")}}</KeyValueView>
                    <KeyValueView title="计费重量" :value="getProductWeight(item)"></KeyValueView>
                    <KeyValueView title="是否有尺码表" :value="getHasSizeTable(item)"></KeyValueView>
                    <KeyValueView title="采集人" :value="item.author"></KeyValueView>
                    <KeyValueView title="所属站点" :value="getStationTag(item)"></KeyValueView>
                  </div>
                  <div>
                    <KeyValueView title="平台" :value="item.from"></KeyValueView>
<!--                    <KeyValueView title="供货商" v-if="item.store!=null">-->
<!--                      {{item.store.shopName}}</KeyValueView>-->
                    <KeyValueView title="供货商编号" :value="item.shopId"></KeyValueView>
                    <KeyValueView title="审核时间" :value="getDateStr(item.auditInfo.auditTime)"></KeyValueView>
                  </div>

                  <div v-if="item.importSummary != null">
                    <KeyValueView title="历史导入成功" v-if="item.importSummary.successNum>0"><span style="color: #4caf50;">{{item.importSummary.successNum}}次</span></KeyValueView>
                    <KeyValueView title="此时排队中" v-if="item.importSummary.waitNum>0"><span style="color:#ff9800;">{{item.importSummary.waitNum}}次</span></KeyValueView>
                    <KeyValueView title="当前正在导入中" v-if="item.importSummary.importingNum>0"><span style="color: #ff9800;">是</span></KeyValueView>
                    <KeyValueView title="导入失败" v-if="item.importSummary.failedNum>0"><span style="color: #f44336;">产品数据 {{item.importSummary.failedNum}}次</span></KeyValueView>
                    <KeyValueView title="导入失败" v-if="item.importSummary.imageFailedNum>0"><span style="color: #f44336;">图片 {{item.importSummary.imageFailedNum}}次</span></KeyValueView>
                  </div>
                </div>

                <div class="item-bottom">
                  <Button type="info" ghost size="small" icon="md-list-box" @click="showImportRecords(item)">历史导入记录</Button>
                  <Button type="error" ghost size="small" icon="md-eye-off" @click="bannedProduct(item.id)" v-if="!stationHasBanned(item)">屏蔽</Button>
                  <Button type="warning" ghost size="small" icon="md-undo" @click="cancelBannedProduct(item.id)" v-if="stationHasBanned(item)">取消屏蔽</Button>
                  <Button type="primary" ghost size="small" icon="md-arrow-forward" @click="showImportDialog([item.id])" v-if="!hasBanned(item)">导入</Button>
                  <Button type="info" ghost size="small" icon="md-information-circle" @click="showViewModal(item)">查看</Button>
                </div>
              </Col>
            </Row>
          </ListItem>
        </CheckboxGroup>
      </div>
      <div v-else>
        <ListItem>
          <div style="width: 100%; text-align: center; color: #ccc;">暂无数据</div>
        </ListItem>
      </div>
    </List>
    <div style="text-align: right; margin-top: 20px;">
      <Page :total="page.total" :page-size="page.pageSize" :current="page.pageNum" @on-change="pageNumChange"
            @on-page-size-change="pageSizeChange" :page-size-opts="page.options"
            show-sizer show-elevator show-total></Page>
    </div>

    <!-- 查看大图 -->
    <Modal v-model="bigImage.isShow" title="查看图片" footer-hide :width="600">
      <div class="big-img-box">
        <img :src="bigImage.src" alt="图片加载失败">
      </div>
    </Modal>

    <!-- 填写利润比 -->
<!--    <Modal v-model="status.profitRatioModal.isShow" :mask-closable="false" title="利润比" :width="600">
      <Form :label-width="75" :model="importParam" inline label-colon>
        <FormItem :label-width="0">
          <RadioGroup v-model="importParam.profitRatio" type="button" button-style="solid">
            <Radio v-for="(ratio, index) in profitRatios" :key="index" :label="ratio">{{ratio+"%"}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="利润比" prop="profitRatio" required :show-message="false" class="one-line">
          <InputNumber v-model="importParam.profitRatio" :min="0" :active-change="false"
                       :formatter="formatProfitRatio" :parser="parseProfitRatio" class="input-common"></InputNumber>
          <div style="color: #888888;font-size: 12px">不得低于 100%</div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="hideProfitRatioModal()">取消</Button>
        <Button type="primary" @click="importToFormalLib()">确定</Button>
      </div>
    </Modal>-->

    <Modal v-model="status.importRecordListModal.isShow" title="导入记录" :width="1100" footer-hide>
      <Row class="y_query_right" style="margin-bottom: 10px;">
        <Button type="info" ghost size="small" icon="md-refresh" @click="reloadRecordList()">刷新</Button>
      </Row>
      <Table border :columns="importRecordColumns" :data="importRecordList" no-data-text="暂无记录"></Table>
    </Modal>

    <Modal v-model="status.viewModal.isShow" :mask-closable="false" title="审核或编辑" :width="1200">
      <Form ref="impProductForm" :model="productParam" :label-width="120" inline label-colon>
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品基本属性：</div>

          <FormItem label="货源编码" prop="pCode">
            {{productParam.pCode}}
          </FormItem>
          <FormItem label="采集链接" prop="sourceUrl">
            <div style=" overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
              <a :href="productParam.sourceUrl" target="_blank" :title="productParam.sourceUrl">{{productParam.sourceUrl}}</a>
            </div>
          </FormItem>


          <FormItem label="产品名称" prop="titleEn" required class="one-line" :show-message="false">
            <Input v-model="productParam.title"></Input>
            <Input v-model.trim="productParam.titleEn" :maxlength="150" style="margin-top: 0.5rem"></Input>
          </FormItem>
          <br/>

          <FormItem label="运费核算重量" prop="weight" required :label-width="140" :show-message="false">
            <Input type="text"  v-model="productParam.weight" style="width: 150px;">
              <span slot="append">g</span>
            </Input>
            <div style="line-height: 20px; margin-top: 5px;">
              <span class="under-tip" style="display: block;" v-for="(item, index) in getWeightAttrs(productParam.attrs)" :key="index">{{item.name}}:{{item.value}}</span>
            </div>
          </FormItem>

          <FormItem label="采集分类" prop="categories" required :show-message="false">
            <Cascader  v-model="productParam.categories" :data="categoryTreeData" change-on-select style="width: 250px;"></Cascader>
          </FormItem>

          <FormItem label="采集标签" prop="tags">
            <Select v-model="productParam.tags" multiple filterable allow-create
                    placeholder="用户不可见,可中文" style="width: 250px;">
              <Option v-for="(tag, index) in status.viewModal.tagList" :key="index" :value="tag">{{tag}}</Option>
            </Select>
          </FormItem>

          <FormItem label="其他货源" prop="otherSourceUrls" class="one-line">
<!--            <Button type="info" ghost icon="md-add" @click="addSourceUrl()">新增备用货源</Button>-->
            <div v-for="(url, index) in productParam.otherSourceUrls" :key="index" style="margin-top: 20px;">
              <!--              <span class="item-name">备用货源-{{index+1}}: </span>-->
              <Input type="text" v-model.trim="productParam.otherSourceUrls[index]" placeholder="备用货源链接" style="max-width: 50%" class="item-input-large"></Input>
<!--              <Button @click="deleteSourceUrl(index)">删除</Button>-->
            </div>
          </FormItem>

        </div>

        <!-- 产品价格 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品价格：</div>
          <FormItem label="价格单位" prop="priceUnit" :label-width="140" required :show-message="false">
            <Select v-model="productParam.priceUnit" style="width: 150px;">
              <Option v-for="(item, index) in dict.priceUnits" :key="index" :value="item.value">{{item.label}} - {{item.value}}</Option>
            </Select>
          </FormItem>

          <FormItem prop="prices" v-for="(item, index) in productParam.prices" :key="index" class="one-line" :label-width="80">
            <span slot="label" class="item-label">{{'第'+(index+1)+'档'}}</span>
            <span class="item-name item-name-count">起订量：</span><Input type="number" v-model="item.begin" style="max-width: 70px"></Input>
            <span class="item-name item-name-price">采集价格 ( {{currency}} ) ：</span><Input type="number" v-model="item.price" :append="currency" placeholder="价格" class="item-input-mini"></Input>
            <span class="item-name"> + 运费成本 ( {{currency}} ) ：</span><Input type="number" v-model="item.shippingCost" placeholder="运费成本" class="item-input-mini"></Input>
            <span class="item-name"> =  保底价格:</span> <span>{{item.usdPrice}}美元</span>
<!--            <Button @click="deletePrice(index)"  style="margin-left: 1rem">删除</Button>-->
          </FormItem>
<!--          <Button type="info" ghost icon="md-add" @click="addPrice()">新增一档起订量与价格</Button>-->
        </div>

        <!-- 尺码表 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品尺码表（可选）：
            <!--            <Button type="primary" icon="md-add" @click="addSizeTable()" style="margin-left: 20px;" v-if="!productParam.hasSizeTable">新增</Button>
                        <Button type="error" icon="md-trash" @click="deleteSizeTable()" style="margin-left: 20px;" v-else>删除</Button>-->
          </div>
          <div>
            <SizeTableTransform v-model="productParam.sizeTable" :editable="false"></SizeTableTransform>
          </div>
        </div>

        <!-- 产品图片 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品图片：</div>
          <FormItem label="主图" prop="mainImgs" class="one-line">
            <Card v-for="(img, index) in productParam.mainImgs" :key="index" class="image-card" style="height: 225px;">
              <div class="image-box" @click="showBigImage(yunPath+img.colorImg)">
                <img :src="getListImgUrl(img.colorImg, productParam)" alt="图片可能还未上传"/>
              </div>
<!--              <div slot="title">
                <span v-if="index == 0">橱窗图</span>
                <a href="javascript:void(0)" @click="moveToFirst(productParam.mainImgs, index)" v-else>设为橱窗图</a>
              </div>
              <div slot="extra" class="extra">
                <Icon type="md-close-circle" @click="deleteImage(1, index)"></Icon>
              </div>-->
            </Card>
          </FormItem>
          <FormItem label="详情图" prop="productImgs" class="one-line">
            <Card v-for="(img, index) in productParam.productImgs" :key="index" class="image-card">
              <div class="image-box" @click="showBigImage(yunPath+img.colorImg)">
                <img :src="yunPath + img.colorImg" alt="图片可能还未上传"/>
              </div>
<!--              <div slot="extra" class="extra">
                <Icon type="md-close-circle" @click="deleteImage(2, index)"></Icon>
              </div>-->
            </Card>
          </FormItem>
        </div>



        <!-- 产品属性 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品属性列表：</div>


          <FormItem v-for="(item, index) in productParam.attrs" :key="index" class="one-line">
            <span slot="label" class="item-label">{{" #"+(index+1)+"："}}</span>
            <div class="attr-item">
              <div class="one-line">
                <span class="attr-name">属性名：</span><Input type="text" v-model="item.nameEn" class="item-input" :maxlength="100" show-word-limit></Input>
                <span class="attr-name"></span><span class="under-tip">{{item.name}}</span>
              </div>
            </div>
            <div class="attr-item">
              <div class="one-line">
                <span class="attr-name">属性值：</span><Input type="text" v-model="item.valueEn" class="item-input" :maxlength="200" show-word-limit></Input>
                <span class="attr-name"></span><span class="under-tip">{{item.value}}</span>
              </div>
            </div>
            <div class="item-button">
<!--              <Button @click="deleteAttribute(index)">删除</Button>-->
            </div>
          </FormItem>
<!--          <Button type="info" ghost icon="md-add" @click="addAttribute()">新增产品属性</Button>-->
        </div>

        <!-- 产品色卡 -->
        <!--        <div class="modal_base_div">
                  <div class="modal_base_div_title">产品色卡：</div>
                  <Table :columns="colorColumns" :data="productParam.colors" border></Table>
                </div>-->

        <div class="modal_base_div">
          <div class="modal_base_div_title">产品色卡列表：</div>
          <List border>
            <ListItem v-for="(item,index) in productParam.colors" style="padding-top: 30px; padding-bottom: 30px;">
              <Row style="width: 100%;">
                <Col :span="3">
                  <div class="one-line" style="text-align: center;">
                    <img :src="getListImgUrl(item.colorImg, productParam)" style="max-width: 100px" @click.stop="showBigImage(yunPath + item.colorImg)">
                  </div>
                  <div class="color-buttons">
<!--                    <Button type="primary" icon="md-create" size="small" @click="showModifyColorModal(index)">修改</Button>-->
<!--                    <Button type="error" icon="md-trash" size="small" @click="deleteProductColor(index)">删除</Button>-->
                  </div>
                </Col>
                <Col :span="20" style="margin-left: 20px;">
                  <div class="one-line">
                    <KeyValueView title="顺序">
                      <Input type="number" v-model="item.position" class="item-input-mini"></Input>
                    </KeyValueView>

                    <KeyValueView :title="item.name">
                      <Input type="text" v-model="item.nameEn" class="item-input" style="margin-left: 5px;"></Input>
                    </KeyValueView>
                  </div>

                  <div v-if="item.sizes!=null"  style="margin: 1rem 0;">
                    <Divider/>
                    <div v-for="(size, sizeIndex) in item.sizes" :key="sizeIndex"  class="one-line" style="padding: 0.5rem 0" >
                      <KeyValueView :title="size.name">
                        <Input type="text" v-model.trim="size.nameEn" class="item-input" style="margin-left: 5px;" :maxlength="40" show-word-limit>
                        </Input>
                      </KeyValueView>
<!--                      <Button @click="modifyOtherColorSizes(size.name, size.nameEn)">同步修改其他色卡</Button>-->
<!--                      <Button type="error" @click="deleteColorSize(item.sizes, sizeIndex)" style="margin-left: 1rem">删除</Button>-->

                    </div>
<!--                    <Button type="info" ghost icon="md-add" @click="addColorSize(item.sizes)">新增尺码</Button>-->
                  </div>
                  <!--                  <div class="one-line" style="margin-top: 10px; text-align: right;">
                                      <Button type="primary" icon="md-create" size="small" @click="showModifyColorModal(index)" style="margin-top: 10px;">修改</Button>
                                      <Button type="error" icon="md-trash" size="small" @click="deleteProductColor(index)" style="margin-top: 10px;">删除</Button>
                                    </div>-->
                </Col>
              </Row>
            </ListItem>
          </List>
        </div>
      </Form>
      <div slot="footer">
        <Button @click="hideViewModal()">关闭</Button>
      </div>
    </Modal>

    <!-- 导入正式库弹窗 -->
    <Modal width="60%" v-model="status.profitRatioModal.isShow" title="导入设置" :mask-closable="false">
      <import-dialog :import-param="importParam"></import-dialog>
      <div slot="footer">
        <Button @click="hideImportDialog()">取消</Button>
        <Button type="primary" @click="importProducts()">导入</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import importData from "./js/productImport/importData";
import {queryMongoCategories} from "./js/product/productFuns";
import {
  initPageInfo,
  importToFormalLib,
  queryProductList,
  bannedProducts,
  cancelBannedProducts,
  queryImportRecordList,
  reImportProduct,
  deleteImportRecord,
  resetImportParams,
  importProducts,
  afterImportProducts
} from "./js/productImport/importFuns";
import KeyValueView from "../widgets/KeyValueView";
import {isEmpty, isNotEmpty} from "../js/commonUtils";
import productData from "./js/product/productData";
import SizeTableTransform from "./sizeTableTransform/SizeTableTransform";
import ImportDialog from "./importDialog/ImportDialog";

export default {
  name: "ProductImport",
  data() {
    return {
      yunPath: this.$store.getters.aliImgPrefix+"products/",
      station: this.$store.getters.siteInfo,
      currency: "¥",
      dict: productData.dict,
      searchParam: importData.tParam.searchParam,
      importParam: importData.tParam.importParam,
      importRecordParam: importData.tParam.importRecordParam,
      productList: importData.tData.list,
      importRecordList: importData.tData.importRecordList,
      selectedRows: [],
      selectedIds: [],
      allCheck: {
        isChecked: false,
        indeterminate: false,
      },
      page: importData.tPage.listPage,
      bigImage: {
        isShow: false,
        src: "",
      },
      profitRatios: [100, 110, 120, 130, 135, 140,145,150,155,165,170,175,180,185,190,200],
      status: importData.tStatus,
      categoryTreeData: [],
      datePickerOptions: productData.dict.datePickerOptions,
      importStates: {
        list: [
          {value: 0, label: "已加入导入队列"},
          // {value: 1, label: "导入数据中"},
          // {value: 2, label: "导入图片中"},
          {value: 1, label: "正在导入"}, //导入过程不再区分导入数据和导入图片
          {value: 3, label: "数据导入失败"},
          {value: 4, label: "图片导入失败"},
          {value: 5, label: "导入成功"},
        ],
        stateWait: 0,
        // stateImportData: 1,
        // stateImportImage: 2,
        stateImporting: 1,
        stateImportFailed: 3,
        stateImportImageFailed: 4,
        stateImportSuccess: 5,
      },
      importTypes: {
        list: [
          {value: 0, label: "等待数据和图片"},
          {value: 1, label: "只导入图片"},
        ],
        typeAll: 0,
        typeOnlyImage: 1,
      },
      productParam: importData.tParam.viewParam,
    }
  },
  components: {
    KeyValueView, SizeTableTransform, ImportDialog
  },
  watch: {
    selectedIds() {
      if(this.selectedIds.length > 0) {
        if(this.selectedIds.length == this.productList.length) {
          this.allCheck.isChecked = true;
          this.allCheck.indeterminate = false;
        }else{
          this.allCheck.isChecked = false;
          this.allCheck.indeterminate = true;
        }
      }else{
        this.allCheck.isChecked = false;
        this.allCheck.indeterminate = false;
      }
    },
  },
  mounted() {
    queryMongoCategories(this, this.categoryTreeData);
    initPageInfo();
  },
  computed: {
    importRecordColumns() {
      let self = this;
      return [
        {title: "产品SKU", minWidth: 150, align: "center", key:"productCode"},
        {title: "利润比", width: 80, align: "center", render: function (h, params) {
            return h("div", params.row.profitRatio+"%");
          }
        },
        {title: "操作人", width: 100, align: "center", key:"createUser"},
        // {title: "货源链接", width: 300, align: "center", key:"sourceUrl"},
        // {title: "运费"+self.currency, width: 150, align: "center", key:"shippingFee"},
        {title: "导入时间", width: 180, align: "center", render: function (h, params){
            return h("div", self.getDateStr(params.row.createTime));
          }
        },
        {title: "导入状态", width: 150, align: "center", render: function (h, params) {
            return h("div", {style: {color: self.getStateColor(params.row.state)}}, self.getImportState(params.row.state));
          }
        },
        {title: "重试次数", width: 100, align: "center", key:"retryTimes"},
        {title: "操作", width: 220, align: "center", fixed: "right", render: function (h, params) {
            let btnTxt = "";
            let importType = 0;
            if(self.isImportFailed(params.row) || self.isImportImageFailed(params.row)) {
              return h("div", [
                h("Button", {
                  props: {type: 'primary', size: 'small', icon: "md-arrow-forward"},
                  style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                  on: {
                    click: () => {
                      self.reImport(params.row);
                    }
                  }
                }, self.isImportFailed(params.row)?"重新导入":"导入图片"),
                h("Button", {
                  props: {type: 'error', size: 'small', icon: "md-arrow-forward"},
                  style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                  on: {
                    click: () => {
                      self.deleteImportRecord(params.row);
                    }
                  }
                }, "删除")
              ]);
            }else{
              return h("");
            }
          }
        },
      ];
    },
    noSelectedRows() {
      // return this.selectedRows == null || this.selectedRows.length == 0;
      return this.selectedIds == null || this.selectedIds.length == 0;
    },
  },
  methods: {
    getProductOriginalImg(row) {
      let imgOriginal = "";
      if(row.mainImgs != null && row.mainImgs.length > 0) {
        imgOriginal = row.mainImgs[0].colorImg;
      }else if(row.colors != null && row.colors.length > 0) {
        imgOriginal = row.colors[0].colorImg;
      }
      return this.yunPath+imgOriginal;
    },
    getProductImg(row) {
      let imgOriginal = this.getProductOriginalImg(row);
      if(isEmpty(imgOriginal)) {
        return "";
      }
      if(this.isItemAuditing(row) || this.isItemAudited(row)) {
        let imgUrl = imgOriginal.substring(0, imgOriginal.lastIndexOf("/"))+"/200w"+imgOriginal.substring(imgOriginal.lastIndexOf("/"))
        return imgUrl;
      }
      return imgOriginal;
    },
    isItemAuditing(item) {
      return item.state == this.dict.stateAuditing;
    },
    isItemAudited(item) {
      return item.state == this.dict.stateAudited;
    },
    getStateColor(state) {
      switch (state) {
        case this.importStates.stateWait:
          return "#2db7f5";
        // case this.importStates.stateImportData:
        // case this.importStates.stateImportImage:
        case this.importStates.stateImporting: //导入过程不再区分导入数据和导入图片
          return "#ff9900";
        case this.importStates.stateImportFailed:
        case this.importStates.stateImportImageFailed:
          return "#ed4014";
        case this.importStates.stateImportSuccess:
          return "#19be6b";
        default:
          return "#2db7f5";
      }
    },
    changeSelectedRows(selection) {
      this.selectedRows.splice(0);
      this.selectedRows.push(...selection);
    },
    toggleAllCheck(isChecked) {
      this.selectedIds.splice(0);
      if(isChecked) {
        let self = this;
        let ids = this.productList.filter(row => !self.hasBanned(row)).map(row => {return row.id});
        this.selectedIds.push(...ids);
      }
    },
    changeTimeParam(dateArr, type) {
      if(isNotEmpty(dateArr[0])){
        this.searchParam.auditStartTime = this.$tiyQueryTime(new Date(dateArr[0]+' 00:00:00').getTime());
        this.searchParam.auditEndTime = this.$tiyQueryTime(new Date(dateArr[1]+' 23:59:59').getTime());
      }
    },
    search() {
      this.resetSelectedProducts();
      importData.tPage.listPage.pageNum = 1;
      queryProductList(this);
    },
    resetSelectedProducts() {
      this.selectedIds.splice(0);
    },
    pageNumChange(pageNum) {
      importData.tPage.listPage.pageNum = pageNum;
      queryProductList(this);
    },
    pageSizeChange(pageSize) {
      importData.tPage.listPage.pageNum = 1;
      importData.tPage.listPage.pageSize = pageSize;
      queryProductList(this);
    },
    getProductState(product) {
      let isImporting = this.isImporting(product);
      if(isImporting) {
        return "导入中";
      }
      let importFailed = this.isImportFailed(product);
      if(importFailed) {
        return "导入失败"
      }
      let hasImported = this.isImported(product);
      if(hasImported) {
        return "已导入";
      }
      return "未导入";
    },
    getLastProductImportState(product) {
      let importFailed = this.isImportFailed(product);
      if(importFailed) {
        return "导入失败"
      }
      let hasImported = this.isImported(product);
      if(hasImported) {
        return "导入成功";
      }
      return "无";
    },
    getProductWeight(item) {
      if(item.weight == null) {
        return "无";
      }
      return item.weight+'g';
    },
    getHasSizeTable(item) {
      if(item.sizeTable == null || item.sizeTable.length == 0) {
        return "无";
      }
      return "有";
    },
    getDateStr(dateTime) {
      if(dateTime == null) {
        return "";
      }
      return this.$tiyBJTime(dateTime);
    },
    showBigImage(imgSrc) {
      this.bigImage.src = imgSrc;
      this.bigImage.isShow = true;
    },
    showImportRecords(item) {
      this.status.importRecordListModal.isShow = true;
      this.importRecordParam.collectionId = item.id;
      queryImportRecordList(this);
    },
    reloadRecordList() {
      queryImportRecordList(this);
    },
    importOneToFormalLib(product) {
      let tip = "确定要将此产品导入正式库吗(重复导入会生成一个新的SKU)？";
      let ids = [product.id];
      this.showImportToFormalLibModal(ids, tip);
    },
    importManyToFormalLib() {
      if(this.selectedIds == null || this.selectedIds.length == 0) {
        this.$Message.warning("请选择要导入的产品！");
        return;
      }
      let tip = "确定要将这些产品导入正式库吗(重复导入会生成一个新的SKU)？";
      let ids = this.selectedIds;
      this.showImportDialog(ids);
    },
    showImportToFormalLibModal(ids, tip) {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: tip,
        onOk() {
          importData.tParam.importParam.ids.splice(0);
          importData.tParam.importParam.ids.push(...ids);
          importData.tParam.importParam.profitRatio = 100;
          importData.tStatus.profitRatioModal.isShow = true;
        }
      });
    },
    hideProfitRatioModal() {
      importData.tStatus.profitRatioModal.isShow = false;
    },
    formatProfitRatio(value) {
      return value + "%";
    },
    parseProfitRatio(value) {
      return value.replace("%", "");
    },
    importToFormalLib() {
      if(this.importParam.profitRatio < 100) {
        this.$Message.error({content: "利润比不得低于100%", duration: 3, closable: true});
        return;
      }
      importToFormalLib(this);
    },
    containsStation(stations) {
      if(stations == null || stations.length == 0) {
        return false;
      }
      let station = stations.find(station => station.code == this.station.code);
      if(station == null) {
        return false;
      }else{
        return true;
      }
    },
    isImportFailed(queue) {
      return queue.state == this.importStates.stateImportFailed;
    },
    isImportImageFailed(queue) {
      return queue.state == this.importStates.stateImportImageFailed;
    },
    stationHasBanned(product) {
      let has = this.containsStation(product.bannedStations);
      return has;
    },
    hasBanned(product) {
      let has = product.hasBanned || this.containsStation(product.bannedStations);
      return has;
    },
    bannedProduct(id) {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要屏蔽此产品吗？",
        onOk() {
          bannedProducts(self, [id]);
        }
      });
    },
    cancelBannedProduct(id) {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要屏蔽此产品吗？",
        onOk() {
          cancelBannedProducts(self, [id]);
        }
      });
    },
    getImportState(state) {
      let element = this.importStates.list.find(element => state == element.value);
      return element==null?"":element.label;
    },
    reImport(queue) {
      let type = this.isImportFailed(queue)?this.importTypes.typeAll:this.importTypes.typeOnlyImage;
      reImportProduct(this, queue, type);
    },
    deleteImportRecord(queue) {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要删除此导入记录吗？",
        onOk() {
          deleteImportRecord(self, queue);
        }
      })
    },
    showViewModal(product) {
      let params = {id: product.id};
      console.log("Test---")
      this.$Spin.show();
      this.$apiImpProduct.queryProduct(params).then(response => {
        this.$Spin.hide();
        if(response.success) {
          this.$refs.impProductForm.resetFields();
          this.initProductParam(response.result);
          importData.tStatus.viewModal.isShow = true;
        }else{
          console.error(response);
          this.$Message.error(response.errorMessage);
        }
      }).catch(() => {
        this.$Spin.hide();
        this.$Message.error("查询产品信息失败！");
      });
    },
    hideViewModal() {
      importData.tStatus.viewModal.isShow = false;
    },
    initProductParam(product) {
      this.productParam.id = product.id;
      this.productParam.createTime = product.createTime;
      this.productParam.title = product.title;
      this.productParam.titleEn = product.titleEn;
      this.productParam.from = product.from;
      this.productParam.author = product.author;
      this.productParam.sourceUrl = product.sourceUrl;
      this.productParam.pCode = product.pCode;
      this.productParam.shippingFee = product.shippingFee;
      if(product.weight==''||product.weight==null){
        let weight = this.getWeightAttrs(product.attrs);
        if(weight.length>0){
          let weightValue = weight[0].value.toLowerCase().trim();
          if(weightValue.endsWith('kg')){
            this.productParam.weight = weightValue.replaceAll("kg").trim()*1000+50;
          }else if(weightValue.toLowerCase().endsWith('g')){
            this.productParam.weight = weightValue.replaceAll("g")+50;
          }
        }else{
          this.productParam.weight = 1000;
        }
      }else{
        this.productParam.weight = product.weight;
      }

      this.productParam.state = product.state;
      this.productParam.hasBanned = product.hasBanned;
      this.productParam.priceUnit = isEmpty(product.priceUnit)?"piece":product.priceUnit;
      this.productParam.prices.splice(0);
      this.productParam.prices.push(...product.prices);
      this.productParam.mainImgs.splice(0);
      this.productParam.mainImgs.push(...product.mainImgs);
      this.productParam.productImgs.splice(0);
      if(product.productImgs != null) {
        this.productParam.productImgs.push(...product.productImgs);
      }
      this.productParam.colors.splice(0);
      if(product.colors != null) {
        this.productParam.colors.push(...product.colors);
      }
      //属性
      this.productParam.attrs.splice(0);
      if(product.attrs != null) {
        this.productParam.attrs.push(...product.attrs);
      }
      //其他货源
      this.productParam.otherSourceUrls.splice(0);
      if(product.otherSourceUrls != null) {
        this.productParam.otherSourceUrls.push(...product.otherSourceUrls);
      }
      //分类
      this.productParam.categories.splice(0);
      if(product.categories != null) {
        this.productParam.categories.push(...product.categories);
      }else{
        this.productParam.categories.push(this.categoryTreeData[0].value);
      }
      //尺码表
      // this.productParam.hasSizeTable = product.hasSizeTable;
      this.productParam.sizeTable.splice(0);
      if(product.sizeTable != null) {
        this.productParam.sizeTable.push(...product.sizeTable);
      }
      //标签
      this.productParam.tags.splice(0);
      this.status.viewModal.tagList.splice(0);
      this.status.viewModal.tagList.push(...this.status.viewModal.defaultTagList);
      if(product.tags != null) {
        this.productParam.tags.push(...product.tags);
        for(let tag of product.tags) {
          let index = this.status.viewModal.tagList.findIndex(element => element == tag);
          if(index < 0) {
            this.status.viewModal.tagList.push(tag);
          }
        }
      }
      //品牌
      this.status.viewModal.brandList.splice(0);
      this.status.viewModal.brandList.push(...this.status.viewModal.defaultBrandList)
      if(product.attrs != null && product.attrs.length> 0 && product.attrs[0].name == "品牌") {
        let brand = product.attrs[0].valueEn;
        if(isNotEmpty(brand) && !this.status.viewModal.brandList.includes(brand)) {
          this.status.viewModal.brandList.push(brand);
        }
      }

      //审核信息
      if(product.auditInfo != null) {
        this.productParam.auditInfo.auditTime = product.auditInfo.auditTime;
        this.productParam.auditInfo.employeeId = product.auditInfo.employeeId;
        this.productParam.auditInfo.employeeName = product.auditInfo.employeeName;
        this.productParam.auditInfo.desc = product.auditInfo.desc;
      }
    },
    getWeightAttrs(attrs) {
      if(attrs == null || attrs.length == 0) {
        return [];
      }
      let weightAttrs = attrs.filter(attr => isNotEmpty(attr.nameEn) && attr.nameEn.toLowerCase().indexOf("weight")>0);
      if(weightAttrs==null || weightAttrs.length == 0) {
        return [];
      }else{
        return weightAttrs;
      }
    },
    getListImgUrl(imgOriginal, item) {
      if(this.isItemAuditing(item) || this.isItemAudited(item)) {
        let imgUrl = imgOriginal.substring(0, imgOriginal.lastIndexOf("/"))+"/200w"+imgOriginal.substring(imgOriginal.lastIndexOf("/"));
        return this.yunPath + imgUrl;
      }
      return this.yunPath + imgOriginal + "?v="+this.imgParam;
    },
    getStationTag(item) {
      if(item.createStation.code == this.station.code) {
        return "本站";
      }else{
        return "其它站点";
      }
    },
    showImportDialog(ids) {
      resetImportParams(ids);
      this.status.profitRatioModal.isShow = true;
    },
    hideImportDialog() {
      this.status.profitRatioModal.isShow = false;
    },
    importProducts() {
      importProducts(this, afterImportProducts);
    },
  }
}
</script>

<style scoped lang="less">
@import  (once,optional)  "../css/base.less";

.one-line {
  width: 100%;
}
.input-common {
  width: 250px;
}
.big-img-box {
  width: 100%;
  min-height: 500px;
  text-align: center;
}
.big-img-box img {
  max-width: 100%;
  vertical-align: middle;
}
.data-list {
  margin: 1rem 0rem;
  line-height: 25px;
}
.list-item {
  .flex-colum-wrap;
  justify-items: left;
  align-items: start;
  .item-checkbox {
    display: inline-block;
    width: 25px;
    height: 25px;
    text-align: center;
    vertical-align: top;
  }
  .item-img {
    width: 130px;
    text-align: center;
    display: inline-block;
  }
  .item-top{
    width: 100%;
    margin-bottom: 5px;
    .flex-row-wrap;
    justify-content: space-between;
  }
  .item-content {
    margin-bottom: 35px;
    text-align: left;
  }
  .item-bottom{
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    display: block;
    //padding: 0 1rem 0.5rem 0;
    cursor: pointer;
    text-align: right;
    button {
      margin-left: 0.5rem;
    }
  }
}
.modal_base_div {
  text-align: left;
  margin-top: 20px;
  padding: 20px;
  border: dotted thin #d1d1d1
}

.modal_base_div_title {
  font-weight: bold;
  text-align: left;
  margin-bottom: 20px
}
.image-card {
  width: 180px;
  height: 180px;
  display: inline-block;
  margin: 10px;
  .image-box {
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
    img {
      max-width: 100%;
      max-height: 100%;
      vertical-align: middle;
    }
  }
  .extra {
    background-color: #ffffff;
    border: 1px solid #ccc;
    cursor: pointer;
    width: 24px;
    height: 24px;
    line-height: 22px;
    border-radius: 13px;
    text-align: center;
    .ivu-icon {
      font-size: 16px;
    }
  }
}
.ivu-card-extra {
  top: 10px !important;
  right: 10px !important;
}
.item-label {
  font-weight: bold;
  font-size: 14px;
}
.item-name {
  display: inline-block;
  text-align: right;
}
.item-name-count {
  width: 60px;
}
.item-name-price {
  width: 120px;
}
.item-size-name {
  display: inline-block;
  width: 80px;
}
.item-input {
  width: 300px;
  margin-right: 10px;
}
.item-input-large {
  width: 800px;
  margin-right: 10px;
}
.item-input-common {
  width: 240px;
  margin-right: 10px;
}
.item-input-small {
  width: 150px;
  margin-right: 10px;
}
.item-input-mini {
  width: 100px;
  margin-right: 10px;
}
.attr-item {
  display: inline-block;
  width: 400px;
  margin-right: 10px;
}
.attr-name {
  display: inline-block;
  width: 60px;
  text-align: right;
}
.item-button {
  display: inline-block;
  vertical-align: top;
}
</style>
